const axios = require('axios');
const ora = require('ora');
const fs = require('fs-extra');
const path = require('path');
const open = require('open');
const execa = require('execa');
const inquirer = require('inquirer');
const {ls, sleep} = require('../utils');
const spinner = ora();

module.exports = async (data, options) => {
    const [shopId] = data;
    spinner.text = '正在搜索店铺';
    let shopInfo;
    try {
        shopInfo = await getMatchShop(shopId);
    } catch (error) {
        spinner.fail(error);
        if (error === '登录失败') {
            await login();
            shopInfo = await getMatchShop(shopId);
        }
    }
    spinner.text = `获取店铺 ${shopInfo.shopName || shopInfo.shopId} 信息成功`;
    const {data: loginData} = await axios.post('https://api.diankeduo.cn/zhili/occ/order/replaceUserLogin', {
        appKey: '4',
        memberId: shopId,
        platform: 8
    });
    open(loginData.result);
    spinner.succeed(`店铺 ${shopInfo.shopName || shopInfo.shopId} 打开成功`);
}

function getMatchShop(shopId) {
    return new Promise(async (resolve, reject) => {
        const {data:listData} = await axios.post('https://api.diankeduo.cn/zhili/query/businessInfoList', {
            appKey: '4',
            serviceName: '经营神器-美团',
            platform: 8,
            param: shopId,
            pageIndex: 1,
            pageSize: 1
        }, {
            headers: {
                token: ls.get('oa.token')
            }
        });
        if (listData.code !== 200) {
            reject('登录失败');
            return;
        }
        const {list} = listData.result;
        if (!list.length) {
            reject('店铺不存在');
            return;
        }
        resolve(list[0]);
    });
}

async function login() {
    // 获取验证码
    spinner.text = 'token失效，需重新登录，请先输入验证码';
    const {
      data: { img, uuid }
    } = await axios.get('https://api.diankeduo.cn/zhili/captchaImage');
    const picBuffer = Buffer.from(img, 'base64');
    const target = path.resolve(process.cwd(), '.temp/vrCode.png');
    await fs.writeFile(target, picBuffer);
    await execa(`code ${target}`);
    const answer = await inquirer.prompt({
      type: 'input',
      message: '请输入验证码',
      name: 'vrCode'
    });
    spinner.text = '正在登录';
    const { username, password } = ls.get('oa');
    const {
      data: { token }
    } = await axios.post('https://api.diankeduo.cn/zhili/login', {
      username,
      password,
      uuid,
      code: answer.vrCode
    });
    ls.set('oa.token', token);
    await fs.remove(target);
    spinner.text = '登录成功';
    await sleep(1500);
}